package cn.sam416.sample.part0302databinding.messagecodesresolver;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.DefaultMessageCodesResolver;
import org.springframework.validation.ValidationUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Locale;
//From: https://www.logicbig.com/tutorials/spring-framework/spring-core/error-codes.html
public class Test {
    @Bean
    OrderValidator validator(){
        return new OrderValidator();
    }

// Remark for query File of ValidationMessages_en_US.properties
//    @Bean
//    public MessageSource messageSource () {
//        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
//        messageSource.setBasename("ValidationMessages");
//        return messageSource;
//    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(Test.class);

        Order order = new Order();
        order.setOrderPrice(BigDecimal.ZERO);
        BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(order, Order.class.getName());
        DefaultMessageCodesResolver messageCodesResolver =
                (DefaultMessageCodesResolver) bindingResult.getMessageCodesResolver();
        messageCodesResolver.setMessageCodeFormatter(DefaultMessageCodesResolver.Format.POSTFIX_ERROR_CODE);
        OrderValidator validator = context.getBean(OrderValidator.class);
        ValidationUtils.invokeValidator(validator, order, bindingResult);
        //Exception detail
        bindingResult.getAllErrors().forEach(e -> System.out.println(Arrays.toString(e.getCodes())));
        //Message Source
        bindingResult.getAllErrors().forEach(e -> System.out.println(context.getMessage(e, Locale.US)));

    }
}
